package feifei.homeworkfei;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/login.action")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置编码字符集
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 登录  判断你有没有注册过
        // 从ServletContext域中取值
        ServletContext context = this.getServletContext();
        // 假设  key-->loginUser  value--->user对象
        List<User> loginUser = (List<User>) context.getAttribute("loginUser");
        // 判断loginUser是否有值
        if (loginUser == null || loginUser.size() == 0) {
            // 代表没有你没有注册过
            // 跳转到注册页面 去注册
            resp.sendRedirect(req.getContextPath() + "/register.html");
        } else {
            // 代表有值
            // 进行登录判断  判断用户名和密码是否正确
            // 获取请求参数值
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            // 遍历 List<User> 中是否存在该用户名和密码值
            // 开关技术
            boolean isSuccess = false;
            for (int i = 0; i < loginUser.size(); i++) {
                if (loginUser.get(i).getUsername().equals(username) && loginUser.get(i).getPassword().equals(password)) {
                    // 代表用户名和密码值是正确的
                    // 跳转到首页
                    //resp.sendRedirect(req.getContextPath() + "/index.html");
                    isSuccess = true;
                    break;
                }
            }
            // 进行登录判断  判断用户名和密码是否正确
            if (isSuccess) {
                // 用户名和密码都正确，跳转到项目首页
                HttpSession session = req.getSession();
                // 创建User对象
                User user = new User(username,password);
                session.setAttribute("login",user);
                resp.sendRedirect(req.getContextPath() + "/index.html");
            } else {
                // 跳转到注册页面  去注册
                resp.sendRedirect(req.getContextPath() + "/register.html");
            }

        }

    }

}
